package Messages;

import java.io.IOException;
import java.sql.SQLException;

import Server.SQLConnection;

import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

import ocsf.server.ConnectionToClient;
/**
 * This class implements the Add User to db
 *   @author Shlomit Yosfan
 * @author Nofar Sutliman
 */
public class MessageAddUser {
	
	private ConnectionToClient client ;
	private String[] str;
	static int row1;
/**
 * Constructor of this class 	
 * @param str
 * @param client
 */
public MessageAddUser(String[] str, ConnectionToClient client){
		
		this.client= client ;
		this.str= str; 
	}//end of constractor

/**
 * Adding  User to the DB	
 * @throws SQLException
 * @throws IOException
 */

public void AddUser(){
	try 
		{
			Statement stmt;
			SQLConnection conn = new  SQLConnection();
		
			java.sql.PreparedStatement ps = conn.getConnection().prepareStatement("SELECT * FROM db.users ;");
				try {

						ResultSet rs= (ResultSet) ps.executeQuery();
						
						row1 = 0;
						while(rs.next()){
							int temp = rs.getInt(1);
								if(row1>temp)
									row1=row1;
									else{
					 				row1=temp;}
						}	
						
						row1=row1+1;
								
						if (!rs.next())
							{

								ps.executeUpdate("INSERT INTO db.users (idUsers,Name,Password,EMail,Role,Connected) VALUES('"+row1+"','"+str[1]+"','"+str[2]+"','"+str[3]+"','"+str[4]+"',0);");
								
								
									client.sendToClient("AddUser");
							}
						else 
							{
							
								client.sendToClient("TheUserAlreadyExsist");
								
							}
  
					}
				catch (SQLException e)
				{	
					e.printStackTrace();
				}
		}
  
  catch (Exception ex )
  	{
	  ex.printStackTrace();
  	}


}



}